<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use common\models\member\Member;

/* @var $this yii\web\View */
/* @var $searchModel common\models\member\MemberSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', '会员列表');
$this->params['breadcrumbs'][] = $this->title;
?>
<?php $this->beginBlock('siderbar'); ?>
<?= $this->render('/layouts/mem-menu') ?>
<?php $this->endBlock(); ?>

<div class="member-index">

    <p>
        <?= Html::a(Yii::t('app', 'Create'), ['create'], ['class' => 'btn btn-success']) ?>
        <button class="btn btn-warning" id="stop" type="button">驳回</button>
        <button class="btn btn-primary" id="start" type="button">审核</button>
        <button class="btn btn-danger" id="alldel" type="button">删除</button>
        <button class="btn btn-primary" id="change" data-toggle="modal" data-target="#movemodel" type="button">会员共享</button>
    </p>


    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
    <?= GridView::widget([
        'id' => "myform",
        'pjax'=>false,
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'containerOptions'=>['style'=>'overflow: auto'], // only set when $responsive = false
        'headerRowOptions'=>['class'=>'kartik-sheet-style'],
        'filterRowOptions'=>['class'=>'filters'],
        'panel'=>[
            'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-globe"></i> 数据列表</h3>',
            'type'=>'default',
            'footer'=>false
        ],
        'toolbar' => ['{export}', '{toggleData}'],
        'pager'=>[
            'options'=>['class'=>'hidden']//关闭自带分页
        ],
        'persistResize'=>false,

        'columns' => [
            [
                'class'=>'kartik\grid\CheckboxColumn',
                'headerOptions'=>['class'=>'my-table'],
            ],
            'username',
            'phone',
            // 'auth_key',
            // 'password_hash',
            // 'password_reset_token',
            'email:email',

            'company',
            
            [
                'attribute' => 'created_at',
                'format' => ['date', 'Y-M-d H:i:s'],
            ],


           [
                'attribute' => 'status',
                'format' => 'html',
                'value' => function ($model) {
                    if ($model->status === $model::STATUS_SUCCESS) {
                        $class = 'label-success';
                    } elseif ($model->status === $model::STATUS_ACTIVE) {
                        $class = 'label-warning';
                    } else {
                        $class = 'label-danger';
                    }

                    return '<span class="label ' . $class . '">' . $model->statusLabel . '</span>';
                },
                'filterType'=>GridView::FILTER_SELECT2,
                'filter'=>Member::getArrayStatus(),
                'filterWidgetOptions'=>[
                    'pluginOptions'=>['allowClear'=>true],
                ],
                'filterInputOptions'=>['placeholder'=>'全部'],
                'format'=>'raw'

            ],
            [
                'attribute' => 'qiyong',
                'format' => 'html',
                'value' => function ($model) {
                    if ($model->qiyong == $model::QIYONG_SUCCESS) {
                        $class = 'label-success';
                    } elseif ($model->qiyong == $model::QIYONG_DELETED) {
                        $class = 'label-warning';
                    } else {
                        $class = 'label-danger';
                    }

                    return '<span class="label ' . $class . '">' . $model->qiyongLabel . '</span>';
                },
                'filterType'=>GridView::FILTER_SELECT2,
                'filter'=>Member::getArrayQiyong(),
                'filterWidgetOptions'=>[
                    'pluginOptions'=>['allowClear'=>true],
                ],
                'filterInputOptions'=>['placeholder'=>'全部'],
                'format'=>'raw'

            ],
            [
                'class' => 'yii\grid\ActionColumn',
                'header' => '操作',
                'template' => '{view}{update}{delete}{memberassign}{memtrack}',
                'headerOptions' => ['width' => '200'],
                'buttons' => [
                    'view' => function ($url, $model, $key) {
                        return  Html::a('&nbsp;&nbsp;<span class="glyphicon glyphicon-eye-open" ><span class="classformat">查看</span></span>', $url, ['title' => '查看'] ) ;
                    },
                    'update' => function ($url, $model, $key) {
                        return Html::a('&nbsp;&nbsp;<span class="glyphicon glyphicon-pencil"><span class="classformat">修改</span></span>', $url, ['title' => '修改'] ) ;
                    },
                    'delete' => function ($url, $model, $key) {
                        return Html::a('&nbsp;&nbsp;<span class="glyphicon glyphicon-trash" ><span class="classformat">删除</span></span>', $url, [
                            'title' => '删除',
                            'data'=>[
                                'confirm'=>'你确定要删除'.$model->username.'吗？',
                                'method'=>'post'
                            ]
                        ] ) ;
                    },
                    'memberassign' => function ($url, $model, $key) {
                        if(Yii::$app->user->identity->getId()==1){
                            return  Html::a('&nbsp;&nbsp;<span class="glyphicon glyphicon-eye-open" data-toggle="modal" data-target="#myModal" data-whatever="'.$model->id.' "><span class="classformat">会员分配</span></span>', '#', ['title' => '会员分配'] ) ;
                        }

                    },
                    'memtrack' => function ($url, $model, $key) {
                        return Html::a('&nbsp;&nbsp;<span class="glyphicon glyphicon-pencil"><span class="classformat">会员跟踪</span></span>', ['memtrack/index','id'=>$model->id], ['title' => '会员跟踪'] ) ;
                    },
                ],
            ],
        ],
    ]); ?>
    <?= \backend\components\GoLinkPager::widget([
        'pagination' => $dataProvider->pagination,
        'go' => true,
    ]); ?>


</div>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">用户列表</h4>
                </div>
                <div class="modal-body">

                    <div class="box">
                        <div class="box-header">
                            <h3 class="box-title">选择分配用户</h3>
                        </div>
                        <!-- /.box-header -->
                        <div class="box-body no-padding">
                            <table class="table table-condensed" >
                                <tbody id="selcttable">



                                </tbody>
                            </table>
                        </div>
                        <!-- /.box-body -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="savemodal">保存</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="movemodel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">用户列表</h4>
                </div>
                <div class="modal-body">

                    <div class="box">
                        <div class="box-header">
                            <h3 class="box-title">选择共享用户</h3>
                        </div>
                        <!-- /.box-header -->
                        <div class="box-body no-padding">
                            <table class="table table-condensed" >
                                <tbody id="changetable">



                                </tbody>
                            </table>
                        </div>
                        <!-- /.box-body -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="changemodal">保存</button>
                </div>
            </div>
        </div>
    </div>
<?php $this->beginBlock('footer_scripts'); ?>
    <script>
        $(document).ready(function(){
            $('#movemodel').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget) // Button that triggered the modal

                // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                var checkboxid = "";
                var selname = '';

                $('input:checkbox[name="selection[]"]:checked').each(function (i) {
                    if (0 == i) {
                        selname = $(this).parent().siblings().html();
                        checkboxid = $(this).val();
                    } else {
                        selname += ("," + $(this).parent().siblings().html());
                        checkboxid += ("," + $(this).val());
                    }
                });
                if(checkboxid==''){
                    alert("没有选择要共享的会员！！");
                    return false;
                }
                var inputhtml = "<tr><th style='width: 10px'>#</th><th>部门</th><th>用户名</th></tr>";
                var url = "<?php echo Url::to(['member/changelist']);?>";
                $.post(url,{'_csrf':'<?php echo yii::$app->request->getCsrfToken();?>'},function (data){
                    var objjson = $.parseJSON(data);
                    $.each(objjson.user, function(name, value) {


                        var group = "未设置";
                        if(value.group){
                            group = value.group.name;
                        }
                        inputhtml+="<tr><td><input type='checkbox' name='checkselect' class='selnew' value='"+value.id+"'/></td><td>"+group+"</td><td>"+value.username+"</td></tr> ";


                    });
                    $('#changetable').html(inputhtml);
                }).error(function() { alert("没有权限")  });
                $('#changemodal').on('click',function(){
                    console.log(checkboxid);

                    var str=[];
                    $(".selnew:checkbox").each(function(){

                        if($(this).is(":checked")){
                            str.push($(this).attr("value"));
                        }
                    })

                    var url = "<?php echo Url::to(['member/changeseluser']);?>";
                    $.post(url,{'memberid':checkboxid,'userid':str,'_csrf':'<?php echo yii::$app->request->getCsrfToken();?>'},function (data){

                        alert("修改成功");
                        var shareurl = "<?php echo Url::to(['member/sharehei']);?>";
                        location.href= shareurl;
                    }).error(function() { alert("没有权限,请联系管理员")  });
                });
            });

            $('#myModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget) // Button that triggered the modal
                var recipient = button.data('whatever') // Extract info from data-* attributes
                // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                var url = "<?php echo Url::to(['member/userlist']);?>";
                $.post(url,{'id':recipient,'_csrf':'<?php echo yii::$app->request->getCsrfToken();?>'},function (data){
                    var objjson = $.parseJSON(data);


                    var inputhtml = "<tr><th style='width: 10px'>#</th><th>部门</th><th>用户名</th></tr><input type='hidden' id='memberid' name='memberid' value='"+objjson.mid+"' />";

                    $.each(objjson.user, function(name, value) {
                        var ischecked = '';
                        if(objjson.uid==value.id){
                            ischecked = "checked=checked";
                        }
                        var group = "未设置";
                        if(value.group){
                            group = value.group.name;
                        }
                        inputhtml+="<tr><td><input type='radio' name='isselect' "+ischecked+" value='"+value.id+"'/></td><td>"+group+"</td><td>"+value.username+"</td></tr> ";


                    });
                    $('#selcttable').html(inputhtml);
                }).error(function() { alert("没有权限")  });
            });
            $('#savemodal').on('click',function(){
                var id =  $('input:radio:checked').val();
                var url = "<?php echo Url::to(['member/changeuser']);?>";
                var memberid = $('#memberid').val();
                console.log(id);
                console.log(memberid);
                $.post(url,{'id':id,'memberid':memberid,'_csrf':'<?php echo yii::$app->request->getCsrfToken();?>'},function (data){

                    alert("修改成功");
                    location.reload();
                }).error(function() { alert("没有权限,请联系管理员")  });
            });
            bindcheck("<?php echo Url::to(['member/start']);?>");
            binduncheck("<?php echo Url::to(['member/stop']);?>");
            binddel("<?php echo Url::to(['member/alldelete']);?>");

        });
    </script>
<?php $this->endBlock(); ?>